﻿using System.Web;
using System.Runtime.CompilerServices;

namespace MedicalManagementSystem.Models
{
    public class DbContext
    {
        private const string HttpContextKey = "RequestObjectContext";

        public static Db Instance
        {
            [MethodImpl(MethodImplOptions.Synchronized)]
            get
            {
                var db = (Db)HttpContext.Current.Items[HttpContextKey];
                if (db == null)
                {
                    db = new Db();
                    HttpContext.Current.Items[HttpContextKey] = db;
                }

                return db;
            }
        }

        /// <summary>
        /// Reset the EF object context and make it work as 'context-per-request'.
        /// </summary>
        /// <see cref="MvcApplication.Application_BeginRequest"/>
        internal static void Reset()
        {
            var db = (Db)HttpContext.Current.Items[HttpContextKey];
            if (db != null)
            {
                HttpContext.Current.Items[HttpContextKey] = null;
                db.Dispose();
            }
        }

    }
}
